<template>
  <div class="app-container">
    <!--标题-->
      <div class="title-container">
        <h3 class="title">通讯录</h3>
      </div>
    <!--查询功能-->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工工号" prop="employeeNumber">
        <el-input
          v-model="queryParams.employeeNumber"
          placeholder="请输入员工工号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
<!--按钮组功能-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['zuzhi:addressList:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['zuzhi:addressList:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
<!--数据展示功能-->
    <el-row :gutter="20">
      <!--部门数据-->
          <el-col :span="4" :xs="24">
            <div class="head-container">
               <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
               />
            </div>
            <div class="head-container">
               <el-tree
                  :data="deptOptions"
                  :props="{ label: 'label', children: 'children' }"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="deptTreeRef"
                  node-key="id"
                  highlight-current
                  default-expand-all
                  @node-click="handleNodeClick"
               />
            </div>
          </el-col>
          <!--员工数据-->
          <el-col :span="20" :xs="24">
            <el-table v-loading="loading" :data="addressListList" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="员工姓名" align="center" prop="name" width="100" />
                  <el-table-column label="工号" align="center" prop="employeeNumber" width="100" />
                  <el-table-column label="部门" align="center" prop="dept.deptName" width="100"/>
                  <el-table-column label="职位" align="center" prop="position.posName" width="100"/>
                  <el-table-column label="手机号码" align="center" prop="phone" />
                  <el-table-column label="邮箱" align="center" prop="email" />
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                      <el-button link type="primary" icon="Edit" @click="viewDetails(scope.row)" v-hasPermi="['zuzhi:addressList:edit']">查看详情</el-button>
                      <el-button link type="primary" icon="Delete" @click="adjustSector(scope.row)" v-hasPermi="['zuzhi:addressList:remove']">调整部门</el-button>

                    </template>
                  </el-table-column>
                </el-table>
          </el-col>
    </el-row>


    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通讯录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="addressListRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 调整部门对话框 -->
    <el-dialog title="调整部门" v-model="adjustDeptDialogVisible" width="500px" append-to-body>
      <el-form ref="adjustDeptFormRef" :model="adjustDeptForm" label-width="80px">
        <el-form-item label="员工姓名">
          <el-input v-model="adjustDeptForm.name" disabled />
        </el-form-item>
        <el-form-item label="当前部门">
          <el-input v-model="adjustDeptForm.currentDept" disabled />
        </el-form-item>
        <el-form-item label="选择部门" prop="departmentId">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleAdjustDeptNodeClick"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="adjustDeptDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAdjustDept">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="AddressList">
//引入
import { updateAddressListDepartment,listAddressList, getAddressList, delAddressList, addAddressList, updateAddressList } from "@/api/zuzhi/addressList"
import {deptTreeSelect} from "@/api/system/user";
import {useRouter} from "vue-router";
//变量定义
const { proxy } = getCurrentInstance()

const addressListList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const deptName = ref("");
const deptOptions = ref(undefined);
const router = useRouter();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    employeeNumber: null,
    phone: null,
    departmentId: undefined,
  },
  rules: {
    name: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/**  通过条件过滤节点*/
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

// 调整部门相关
const adjustDeptDialogVisible = ref(false)
const adjustDeptForm = reactive({
  id: null,
  name: '',
  currentDept: '',
  departmentId: null
})
let selectedRow = ref({})

//方法
function submitAdjustDept() {
  if (!adjustDeptForm.departmentId) {
    proxy.$modal.msgError('请选择一个部门')
    return
  }

  // 调用接口更新部门
  updateAddressListDepartment({
    id: adjustDeptForm.id,
    departmentId: adjustDeptForm.departmentId
  }).then(response => {
    proxy.$modal.msgSuccess('调整成功')
    adjustDeptDialogVisible.value = false
    getList() // 刷新列表
  })
}

function adjustSector(row) {
  selectedRow.value = row
  adjustDeptForm.id = row.id
  adjustDeptForm.name = row.name
  adjustDeptForm.currentDept = row.dept?.deptName || '无'
  adjustDeptDialogVisible.value = true
}

function handleAdjustDeptNodeClick(node) {
  adjustDeptForm.departmentId = node.id
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.departmentId = data.id;
  handleQuery();
};
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询通讯录列表 */
function getList() {
  loading.value = true
  listAddressList(queryParams.value).then(response => {
    addressListList.value = response.rows
    console.log(addressListList.value);
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    avatar: null,
    name: null,
    employeeNumber: null,
    departmentId: null,
    phone: null,
    positionId: null,
    type: null,
    idNumber: null,
    email: null,
    hireDate: null,
    certificateId: null,
    contractId: null,
    gender: null,
    status: null,
    insurancePlanId: null,
    delFlag: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("addressListRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加通讯录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getAddressList(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改通讯录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["addressListRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAddressList(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAddressList(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除通讯录编号为"' + _ids + '"的数据项？').then(function() {
    return delAddressList(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('zuzhi/addressList/export', {
    ...queryParams.value
  }, `addressList_${new Date().getTime()}.xlsx`)
}

getDeptTree();
getList()
</script>

<style scoped lang="scss">
.title-container {
  position: relative;
  padding: 10px 15px;
  margin-bottom: 20px;
}

.title-container::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: #409EFF; /* 蓝色 */
}

.title {
  font-size: 20px;
  color: #333;
  margin: 0;
  line-height: 1;
}

/* 分隔线 */
.title-container::after {
  content: '';
  display: block;
  margin-top: 10px;
  border-top: 1px solid #ebeef5; /* 淡淡的分隔线 */
}

</style>
